package com.xsq.netty;

import com.xsq.netty.channel.INettyChannelListener;
import com.xsq.netty.utils.LogUtils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by Shiquan.Xiao on 2023/2/23.
 */
public class NettyReadMsgHandler extends ChannelHandlerAdapter {

    private final NettyConnection nettyConnection;

    public NettyReadMsgHandler(NettyConnection nettyConnection) {
        this.nettyConnection = nettyConnection;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        LogUtils.i(NettyHelper.TAG,"channelActive方法执行");
        if (nettyConnection.getListener() != null) {
            nettyConnection.getListener().onConnect();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        LogUtils.e(NettyHelper.TAG,"channelInactive方法执行"+Thread.currentThread());
        ctx.close();
        if (nettyConnection.getListener() != null) {
            nettyConnection.getListener().onFailed();
        }
        nettyConnection.closeConnect();
        Thread.sleep(5000);
        if (nettyConnection.haveConnection()) {
            return;
        }
        nettyConnection.connect();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        LogUtils.e(NettyHelper.TAG,"exceptionCaught方法执行, 异常信息："+cause.getMessage()+Thread.currentThread());
        ctx.close();
        if (nettyConnection.getListener() != null) {
            nettyConnection.getListener().onFailed();
        }
        nettyConnection.closeConnect();
        Thread.sleep(5000);
        if (nettyConnection.haveConnection()) {
            return;
        }
        nettyConnection.connect();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Channel channel = ctx.channel();
        String channelId = "";
        if (channel != null) {
            channelId = channel.id().toString();
        }
        LogUtils.i(NettyHelper.TAG,"channel id: "+channelId+" 接收服务器消息："+msg);
        INettyChannelListener listener = nettyConnection.getListener();
        if (listener != null) {
            String message = "";
            if (msg != null) {
                message = msg.toString();
            }
            listener.onMessage(message);
        }
    }

}
